package com.vk.project.common;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.Data;

import java.io.Serializable;

/**
 * @ClassName : BaseResponse
 * @Description : 通用返回类
 * @Author : LYQ
 * @Date: 2024-01-25 13:54
 */
@Data
public class BaseResponse<T> implements Serializable {

    /**
     * 响应码
     */
    private int code;

    /**
     * 响应数据
     */
    private T data;

    /**
     * 响应信息
     */
    private String message;

    public BaseResponse(int code, T data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    public BaseResponse(int code, T data) {
        this(code, data, "");
    }

    public BaseResponse(ErrorCode errorCode) {
        this(errorCode.getCode(), null, errorCode.getMessage());
    }

    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(200, data, "请求成功");
    }

    public static <T> BaseResponse<T> success() {
        return success(null);
    }

    public static <T> BaseResponse<T> unauthorized(String message) {
        return failure(401, message);
    }

    public static <T> BaseResponse<T> forbidden(String message) {
        return failure(403, message);
    }

    public static <T> BaseResponse<T> failure(int code, String message) {
        return new BaseResponse<>(code, null, message);
    }

    public String asJsonString() {
        return JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls);
    }
}
